package com.trainingcloud.action.user;

import java.util.Date;

import com.trainingcloud.XMLSerializer;
import com.trainingcloud.action.BaseSessionAction;
import com.trainingcloud.dao.RoleDAO;
import com.trainingcloud.dao.UserDAO;
import com.trainingcloud.entity.Role;
import com.trainingcloud.entity.User;
import com.trainingcloud.exception.DAOException;
import com.trainingcloud.exception.SystemException;

public class UpdateUserAction extends BaseSessionAction 
{
	private int userId;
	private String loginName;
	private String loginPassword;
	private String name;
	private String email;
	private int roleId;
	private boolean active;
	
	public UpdateUserAction() throws SystemException 
	{
		super();
	}

	@Override
	public String callWithSession() throws DAOException, SystemException 
	{
		if(!currentUser.getRole().isUserManagement())
		{
			return "No access";
		}
		UserDAO userDAO = new UserDAO();
		User user = userDAO.getUserById(userId);
		if(user==null)
		{
			return "Invalid user id.";
		}
		if(name.isEmpty())
		{
			return "User name can't be empty.";
		}
		if(email.isEmpty())
		{
			return "Email can't be empty.";
		}
		RoleDAO roleDAO = new RoleDAO();
		Role role = roleDAO.getRoleById(roleId);
		if(role==null)
		{
			return "Invalid role id.";
		}
		user.setLoginName(loginName);
		if(loginPassword!=null && !loginPassword.isEmpty())
			user.setLoginPassword(loginPassword);
		user.setName(name);
		user.setEmail(email);
		user.setRole(role);
		user.setUpdateTime(new Date());
		user.setActive(active);
		userDAO.updateUser(user);
		
		XMLSerializer.userToXML(user, responseElement);
		
		return null;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getLoginPassword() {
		return loginPassword;
	}

	public void setLoginPassword(String loginPassword) {
		this.loginPassword = loginPassword;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getRoleId() {
		return roleId;
	}

	public void setRoleId(int roleId) {
		this.roleId = roleId;
	}

	public boolean isActive() {
		return active;
	}

	public void setActive(boolean active) {
		this.active = active;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
	
}
